
<template>
  <div class="shopclass" style="-webkit-overflow-scrolling: touch;overflow: hidden;">
    <div class="searchHight sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff px-28rpx pb-32rpx">
      <div class="z-999 flex items-center justify-between" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
        <uni-icons type="back" size="28" />
        <span class="flex-1 text-36rpx" style="text-align: center;">分类</span>
      </div>
      <div class="mt-32rpx flex items-center">
        <div class="relative w-full">
          <input
            v-model.trim="searchVal"
            class="h-68rpx rounded-50 bg-hex-f5f5f5 pl-100rpx"
            placeholder-class="text-hex-CBCBCBFF text-26rpx font-400"
            type="text"
            placeholder="养生膳食" @confirm="onKeyboardConfirm">
          <div class="absolute left-32rpx top-50% h-40rpx w-40rpx translate-y-(-50%)">
            <image :src="`${cdnUrl}/imgs/shop/goodsSearchicon.png${imgVersion}`" mode="scaleToFill"
                   class="h-44rpx w-44rpx" />
          </div>
        </div>
        <div class="flex-1 whitespace-nowrap pl-32rpx pr-20rpx text-28rpx text-hex-999">
          取消
        </div>
      </div>
    </div>
    <div class="box-border flex rounded-t-32rpx pt-32rpx" :style="{ height: `calc(100vh - ${searchHightconut}px)` }" style="-webkit-overflow-scrolling: touch;overflow: auto;">
      <div class="box-border w-192rpx overflow-y-auto bg-hex-f5f5f5">
        <div v-for="(item, index) in menus" :key="index" class="h-90rpx w-full flex items-center"
             :class="[{
               'bg-hex-fff': index === classIndex,
               'bg-hex-f5f5f5': index !== classIndex,
               'rounded-tr-20rpx': index === classIndex + 1,
               'rounded-br-20rpx': index === classIndex - 1,
             }]" @click="switchChange(index)">
          <div :class="classIndex === index ? 'bg-hex-ABCD03' : 'bg-hex-f5f5f5'"
               class="h-46rpx w-6rpx rounded-5rpx bg-hex-ABCD03" />
          <div :class="classIndex === index ? 'font-600 text-hex-333' : ''"
               class="w-full text-center text-28rpx font-500 text-hex-999">{{ item.name }}</div>
        </div>
      </div>
      <div class="flex-1 overflow-hidden px-32rpx">
        <!--  二级筛选 -->
        <scroll-view
          :scroll-x="true" :scroll-with-animation="true"
          :scroll-into-view="scrollIntoViewId"
          class="sticky left-0 right-0 top-0 z-8 h-84rpx w-100% bg-hex-ffffff"
          style="white-space: nowrap">
          <div class="flex">
            <div class="mr-32rpx h-50rpx rounded-50rpx pl-20rpx pr-20rpx text-28rpx leading-50rpx" :class="highlightIndex===0?'bg-[rgb(24,167,134,0.07)] text-hex-ABCD03':'text-hex-333 bg-hex-F5F5F5'" @click="hendAll">全部</div>
            <block v-for="(item, index) in secondaryMenus" :key="index">
              <div :id="`item-${index}`"
                   class="mr-32rpx h-50rpx rounded-50rpx pl-20rpx pr-20rpx text-28rpx leading-50rpx" :data-index="index"
                   :class="highlightIndex===index+1?'bg-[rgb(24,167,134,0.07)] text-hex-ABCD03':'text-hex-333 bg-hex-F5F5F5'" @click="scrollToFirst(index, item)">{{ item.name }}</div>
            </block>
          </div>
        </scroll-view>
        <mescroll-uni
          :up="{
            isBounce: true,
            offset: 150,
            auto: false,
          }"
          :down="{
            textInOffset: '下拉切换',
            textOutOffset: '释放进入',
          }"
          :bottom="100"
          :bottomOffset="100"
          :height="`calc(100vh - ${searchHightconut}px)`"
          @down="downCallback"
          @up="upCallback">
          <!-- 三级导航 -->
          <div v-for="item in shopData" class="items-right mb-32rpx flex" @click="goodsDatails(item)">
            <div class="bg-water box-border w-180rpx flex items-center justify-center rounded-xl bg-hex-fff p-10rpx">
              <image
                class="will-change h-100% w-100% rounded-24rpx"
                lazy-load
                :src="item.productImage" mode="widthFix" />
            </div>
            <div class="ml-20rpx flex flex-1 flex-col justify-between">
              <div class="textHide2 text-24rpx font-500 text-hex-333">{{ item.productName??item.productIntro }}</div>
              <div v-if="item.newState===1" class="w-48rpx rounded-5rpx bg-hex-FFF2E3 p-3rpx text-20rpx font-500 text-hex-E89C43">上新
              </div>
              <div class="flex items-end justify-between">
                <div class="flex items-end">
                  <div class="text-32rpx font-400 text-hex-ff4d4e">¥{{ item.productPrice }}</div>
                  <div class="textdecor ml-10rpx text-24rpx font-500 text-hex-999">￥{{ item.cost }}</div>
                </div>
                <image :src="`${cdnUrl}/imgs/shop/cart-icon.png${imgVersion}`" mode="scaleToFill"
                       class="h-44rpx w-44rpx" />
              </div>
            </div>
          </div>
          <div v-if="shopData.length===0"
               class="flex items-center justify-center">
            <div>
              <image
                class="h-364rpx w-364rpx"
                :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
                mode="scaleToFill"
              />
              <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
            </div>
          </div>
          <div v-if="nextFlag&&menus.length>classIndex+1">
            <uni-load-more status="more" :contentText="{
              contentdown: `上拉进入${menus[classIndex+1]?.name}`,
            }" />
          </div>
        </mescroll-uni>
      </div>
    </div>
  </div>
</template>


<script lang='ts' setup>
import mescrollUni from 'mescroll-uni'

const { addhistoryList } = useShopSeach()
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
let searchVal = $ref('')
const onKeyboardConfirm = (e) => {
  if (e.detail.value.trim() === '') {
    return
  }
  addhistoryList(searchVal)
  navTo(`/pages-shop/shopoutcome?title=搜索&q=${searchVal}`)
  searchVal = ''
}
let searchBarTop: any = $ref('24')
let classIndex: number = $ref(0)
let highlightIndex = $ref(0)
let scrollIntoViewId = $ref('')
let shopClassId = $ref(0)
let isAll = $ref(false)
const switchChange = (val) => {
  classIndex = val
}
//重置分页数
const resetPageNo = () => pageNo = 1
//点击全部
const hendAll = () => {
  resetPageNo()
  shopData = []
  highlightIndex = 0
  shopClassId = menus[classIndex].id
  isAll = true
  getShopList(menus[classIndex].id)
}
//二级菜单点击
const scrollToFirst = (index, item) => {
  resetPageNo()
  shopData = []
  highlightIndex = index + 1
  scrollIntoViewId = `item-${index}`
  shopClassId = item.id
  isAll = false
  getShopList(item.id)
}
let shopData: any = $ref([])
const goodsDatails = (item) => {
  navTo(`/pages-shop/goodsdetails?productId=${item.productId}`)
}

let nextFlag = $ref(false)
let menus: any = $ref([])
//获取菜单
const getMenus = async () => {
  const { status, data, error } = await Fetch('/qqyapi/product/category/queryCategory', {
    method: 'post',
    data: { appType: 3 },
  })
  if (status !== 200 || data.code !== 0) {
    return
  }
  menus = data.result
  getSecondaryMenus(menus[classIndex].id, menus[classIndex].level + 1)
  shopClassId = menus[classIndex].id
  isAll = true
  getShopList(menus[classIndex].id)
}
let secondaryMenus = $ref([])
let shopTotalPage = $ref(0)
let pageNo = $ref(1)
//获取二级菜单
const getSecondaryMenus = async (pid, level) => {
  const { status, data, error } = await Fetch('/qqyapi/product/category/queryCategory', {
    method: 'post',
    data: { appType: 3, pid, level },
  })
  if (status !== 200 || data.code !== 0) {
    return
  }
  secondaryMenus = data.result
}
//获取商品数据
const getShopList = async (id) => {
  const { status, data, error } = await Fetch('/qqyapi/product/product/categoryArea/queryCategoryLinkProduct', {
    method: 'get',
    data: { appType: 3, categoryId: id, pageNo, pageSize: 10, isLinkChildrenNodeQuery: isAll },
  })
  if (status !== 200 || data.code !== 0) {
    return
  }
  shopData = [...shopData, ...data.result.list]
  shopTotalPage = data.result.totalPage
}
//监听菜单改变请求数据
watch(() => classIndex, () => {
  nextFlag = false
  shopData = []
  highlightIndex = 0
  resetPageNo()
  shopClassId = menus[classIndex].id
  isAll = true
  getShopList(menus[classIndex].id)
  getSecondaryMenus(menus[classIndex].id, menus[classIndex].level + 1)
})
onLoad(() => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
const downCallback = (mescroll) => {
  if (classIndex > 0) {
    classIndex -= 1
    mescroll.scrollTo(0, 0)
  }
  mescroll.endErr()
}

const upCallback = useDebounceFn((mescroll) => {
  if (nextFlag) {
    if (classIndex !== menus.length - 1) {
      classIndex += 1
      mescroll.scrollTo(0, 0)
    }
  } else {
    if (pageNo !== shopTotalPage) {
      //上拉加载
      pageNo++
      getShopList(shopClassId)
    }
  }
  if (pageNo === shopTotalPage) nextFlag = true
  mescroll.endErr()
}, 1000)
let searchHightconut = $ref(0)
onMounted(() => {
  getMenus()
  uni
    .createSelectorQuery()
    .selectAll('.searchHight')
    .boundingClientRect((rect: any) => {
      searchHightconut = rect[0].height + 10
    })
    .exec()
})
</script>

<route lang="json">
{"style":{"disableScroll":true}}
</route>

<style lang="scss">
.shopclass {
  .textHide2 {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }

  ::-webkit-scrollbar {
    display: none;
  }
}

</style>
